<template>
  <!-- 添加或修改博客对话框 -->
  <vxe-modal :title="title" v-model="open" width="60%" showFooter show-zoom resize>
    <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">


      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别" prop="category">
            <el-select v-model="form.category" placeholder="请选择类别">
              <el-option
                v-for="dict in dict.type.blog_cat"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="封面" prop="cover">
        <image-upload v-model="form.cover"/>
      </el-form-item>
      <!-- AI摘要生成区域 -->
      <el-form-item label="文章摘要" prop="summary">
        <div class="ai-summary-section">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要或使用AI生成"
            maxlength="200"
            show-word-limit
          />
          <el-button
            type="primary"
            icon="el-icon-cpu"
            size="small"
            @click="generateSummary"
            :loading="summaryLoading"
            style="margin-top: 10px;"
          >
            AI生成摘要
          </el-button>

          <div v-if="aiSummaryPreview" class="summary-preview">
            <h4>AI生成摘要预览:</h4>
            <p>{{ aiSummaryPreview }}</p>
            <el-button
              size="mini"
              @click="applySummary"
              type="success"
            >
              使用此摘要
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="内容">
        <editor v-model="form.content" :height="300"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer  dialog-footer-center">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </vxe-modal>
</template>

<script>
import {addBlog, getBlog, updateBlog} from "@/api/lundao/blog";

export default {
  name: "AddOrUpdateBlog",
  dicts: ['blog_cat'],
  data() {
    return {
      open: false, //是否弹出弹窗
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        cover: [
          {required: true, message: "封面不能为空", trigger: "blur"}
        ],
        content: [
          {required: true, message: "内容不能为空", trigger: "blur"}
        ],
        category: [
          {required: true, message: "类别不能为空", trigger: "change"}
        ],
      },
      // AI摘要相关
      aiSummaryPreview: "", // AI生成的摘要预览
      summaryLoading: false // 加载状态
    }
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加博客";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const blogId = row.blogId
      getBlog(blogId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改博客";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          if (this.form.blogId != null) {
            updateBlog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok')
            });
          } else {
            addBlog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('ok')
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        blogId: null,
        title: null,
        summary: null, // 添加摘要字段
        cover: null,
        content: null,
        category: null,
        views: null,
        userId: null,
        createTime: null
      };
      this.aiSummaryPreview = "";
      this.resetForm("formDialog");
    },
    // AI生成摘要
    async generateSummary() {
      if (!this.form.content || this.form.content.length < 100) {
        this.$message.warning('内容太少，请先输入更多内容');
        return;
      }

      this.summaryLoading = true;
      try {
        // 调用后端AI摘要生成接口
        const response = await this.$http.post('/api/ai/generate-summary', {
          content: this.form.content,
          title: this.form.title
        });

        if (response.data.code === 200) {
          this.aiSummaryPreview = response.data.data.summary;
          this.$message.success('摘要生成成功');
        } else {
          this.$message.error('摘要生成失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('AI摘要生成错误:', error);
        // 模拟AI生成摘要（实际使用时请删除）
        this.simulateAISummary();
      } finally {
        this.summaryLoading = false;
      }
    },
    // 应用摘要到表单
    applySummary() {
      this.form.summary = this.aiSummaryPreview;
      this.$message.success('摘要已应用到博客');
    },
    // 模拟AI生成摘要（开发测试用）
    simulateAISummary() {
      const content = this.form.content || '';
      // 简单提取前100个字符作为摘要
      let summary = content.replace(/<[^>]+>/g, "").substring(0, 100);
      if (content.length > 100) {
        summary += "...";
      }
      this.aiSummaryPreview = summary;
      this.$message.info('使用简易摘要生成（实际应连接AI服务）');
    }
  }
}
</script>

<style scoped>
.ai-summary-section {
  margin-bottom: 10px;
}

.summary-preview {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #67c23a;
}

.summary-preview h4 {
  margin-top: 0;
  color: #303133;
  font-size: 14px;
  margin-bottom: 8px;
}

.summary-preview p {
  margin: 0 0 10px 0;
  color: #606266;
  line-height: 1.5;
}
</style>

<style scoped lang="scss">
// 可以添加更多的样式定制
</style>
